Regular expressions are special strings that are used to describe a search pattern. They can be used for data validation, data processing and pattern matching.

Regular Expressions (regex for short) are language and platform independent so an expression for Perl will work on PHP and C#. Regex start with a caret (^) character and end with a dollar ($) symbol. The text in between these two characters is used to match a string.

A good introduction regular expressions, pattern matching and syntax can be found on Zytrax.com

Regular expressions in C# are defined within the System.Text.RegularExpressions namespace which provides a Regex class. When instantiating the class you need to pass the expression string to the constructor. We have used a verbatim string for the regex as it makes the regex easier if you don't have to escape forward slashes.

In this example we test two strings to see if they contain a valid email address. The emailRegex will match any valid email address.

string ValidEmailAddress = "somebody@somedomain.com";
string InvalidEmailAddress = "invalid.email-address.com&somedomann..3";
string emailRegex = @"^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$";

Regex RegularExpression = new Regex(emailRegex);

if (RegularExpression.IsMatch(ValidEmailAddress))
  Console.WriteLine("{0}: is Valid Email Address", ValidEmailAddress);
else
  Console.WriteLine("{0}: is NOT a Valid Email Address", ValidEmailAddress);

if (RegularExpression.IsMatch(InvalidEmailAddress))
  Console.WriteLine("{0}: is Valid Email Address", InvalidEmailAddress);
else
  Console.WriteLine("{0}: is NOT a Valid Email Address", InvalidEmailAddress);

Regular Expressions can be used for input validation, but they can also be used for search and replace functions, extracting values from a string, ASP.Net Input Validation, web.config ISAPI rewrite rules and many other uses.

 

Tutorials in this Series